﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.ExpressionTool.Visitor
{
    public class OperationsVisitor : ExpressionVisitor
    {
        public Expression Modify(Expression expression)
        {
            Console.WriteLine(expression.ToString());

            //ExpressionVisitor:
            //1.Visit方法--访问表达式目录树的入口---分辨是什么类型的表达式目录
            //2.调度到更加专业的方法中进一步访问,访问一遍之后，生成一个新的表达式目录   ---有点像递归，不全是递归；
            //3.因为表达式目录树是个二叉树，ExpressionVisitor一直往下访问，一直到叶节点；那就访问了所有的节点
            //4.在访问的任何一个环节，都可以拿到对应当前环节的内容(参数名称、参数值。。)，就可以进一步扩展
            return this.Visit(expression);
        }

        /// <summary>
        /// 覆写父类方法；
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        protected override Expression VisitBinary(BinaryExpression b)
        {
            if (b.NodeType == ExpressionType.Add)
            {
                Expression left = this.Visit(b.Left);
                Expression right = this.Visit(b.Right);
                return Expression.Subtract(left, right);
            }
            else if (b.NodeType == ExpressionType.Multiply) //如果是相乘
            {
                Expression left = this.Visit(b.Left);
                Expression right = this.Visit(b.Right);
                return Expression.Divide(left, right); //相除
            }
            return base.VisitBinary(b);
        }

        /// <summary>
        /// 覆写父类方法
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        protected override Expression VisitConstant(ConstantExpression node)
        {
            return base.VisitConstant(node);
        }
    }
}
